<script setup>
import { onMounted, ref } from "vue"
import { ElMessage } from 'element-plus';
// 引入
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { addGoods, getBrandList, getSupplierList, updateGoods } from "../../api/goods"
import { getCategoryList } from '@/api/category'
const emits = defineEmits(['getData'])
const formGoods = ref({
  id: '',
  title: '',
  subTitle: '',
  categoryId3: '',
  description: '',
  content: '',
  brandId: '',
  supplierId: '',
})

const goodsTableData = ref([
  {
    id: '',
    price: '',
    realPrice: '',
    code: '',
    unit: '',
    productWeight: '',
    productLength: '',
    productWidth: '',
    productHeight: '',
    productVolume: ''
  }
])

const deleteRow = (index) => {
  goodsTableData.value.splice(index, 1)
}

const onAddItem = () => {
  goodsTableData.value.push({
    id: '',
    price: '',
    realPrice: '',
    code: '',
    unit: '',
    productWeight: '',
    productLength: '',
    productWidth: '',
    productHeight: '',
    productVolume: ''
  })
}

const dialogVisible = ref(false)
const title = ref('')

// 重置表单数据
const reset = () => {
  dialogVisible.value = false
  clear()
  emits('getData')
}
//清空表单数据
const clear = () => {
  formGoods.value = {
    id: '',
    title: '',
    subTitle: '',
    categoryId3: '',
    description: '',
    content: '',
    brandId: '',
    supplierId: ''
  }

  goodsTableData.value = [
    {
      id: '',
      price: '',
      realPrice: '',
      code: '',
      unit: '',
      productWeight: '',
      productLength: '',
      productWidth: '',
      productHeight: '',
      productVolume: ''
    }
  ]
}

// 品牌列表数据
const brandOptions = ref([])
// 查询所有品牌
const brandsList = async () => {
  let res = await getBrandList()
  brandOptions.value = res.data.map(item => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
// 供应商列表数据
const supplierOptions = ref([])
// 获取所有供应商
const supplierList = async () => {
  let res = await getSupplierList()
  supplierOptions.value = res.data.map(item => {
    return {
      value: item.id,
      label: item.supplierName
    }
  })
}
// 获取所有分类级联
const categoryOptions = ref([])
const categoryProps = ref({
  expandTrigger: 'hover',
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: false,
  checkStrictly: false
})
const categoryList = async () => {
  let res = await getCategoryList()
  categoryOptions.value = res.data
}
const handleCategoryChange = (value) => {
  formGoods.value.categoryId3 = value
}

// 表单校验
const rules = {
  title: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  categoryId3: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择商品品牌', trigger: 'change' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  realPrice: [
    { required: true, message: '请输入商品真实价格', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入商品编码', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入选择', trigger: 'change' }
  ],
  productWeight: [
    { required: true, message: '请输入商品重量', trigger: 'blur' }
  ],
}
const ruleFormRef = ref()
// 提交数据到后端
const submitData = async () => {
  const payload = {
    spuInfo: formGoods.value,
    skuList: goodsTableData.value
  }
  if (!ruleFormRef) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let result = null
      if (formGoods.value.id) {
        result = await updateGoods(payload)
        if (result.code === 200) {
          ElMessage.success('修改成功')
          emits('getData')
        } else {
          ElMessage.error('修改失败')
        }
      } else {
        result = await addGoods(payload)
        if (result.code === 200) {
          ElMessage.success('添加成功')
          emits('getData')
        } else {
          ElMessage.error('添加失败')
        }
      }
      // 重置表单
      reset()
      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
onMounted(() => {
  brandsList()
  supplierList()
  categoryList()
})
defineExpose({
  dialogVisible,
  title,
  formGoods,
  goodsTableData,
  clear,
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="800" :close-on-click-modal="false">
    <span>
      <div>
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form ref="ruleFormRef" :rules="rules" :model="formGoods" label-width="100px">
              <el-form-item label="商品标题:" prop="title">
                <el-input v-model="formGoods.title" placeholder="请输入商品标题"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="ruleFormRef" :model="formGoods" label-width="100px">
              <el-form-item label="商品副标题:">
                <el-input v-model="formGoods.subTitle" placeholder="请输入商品副标题"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="ruleFormRef" label-width="100px">
              <el-form-item label="商品描述:">
                <el-input v-model="formGoods.description" placeholder="请输入商品描述"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form ref="form" :model="formGoods" label-width="100px">
              <el-form-item label="商品详情内容:">
                <div class="editor">
                  <QuillEditor v-model:content="formGoods.content" contentType="html" theme="snow" :toolbar="[
                    ['bold', 'italic', 'underline', 'strike'],
                    ['blockquote', 'code-block'],
                    [{ 'header': 1 }, { 'header': 2 }],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    [{ 'script': 'sub' }, { 'script': 'super' }],
                    [{ 'indent': '-1' }, { 'indent': '+1' }],
                    [{ 'direction': 'rtl' }],
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'font': [] }],
                    [{ 'align': [] }],
                    ['clean'],
                    ['link', 'image', 'video']
                  ]" class="rich-text-editor" />
                </div>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form ref="ruleFormRef" :rules="rules" :model="formGoods" label-width="100px">
              <el-form-item label="商品类别:" prop="categoryId3">
                <el-cascader v-model="formGoods.categoryId3" :options="categoryOptions" :props="categoryProps"
                  @change="handleCategoryChange" clearable style="width: 100%" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="ruleFormRef" :rules="rules" :model="formGoods" label-width="100px">
              <el-form-item label="品牌:" prop="brandId">
                <el-select v-model="formGoods.brandId" placeholder="请选择品牌" clearable style="width: 100%">
                  <el-option v-for="brand in brandOptions" :key="brand.value" :label="brand.label"
                    :value="brand.value" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="ruleFormRef" :rules="rules" :model="formGoods" label-width="100px">
              <el-form-item label="供应商:" prop="supplierId">
                <el-select v-model="formGoods.supplierId" placeholder="请选择供应商" clearable style="width: 100%">
                  <el-option v-for="supplier in supplierOptions" :key="supplier.value" :label="supplier.label"
                    :value="supplier.value" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <!-- sku 信息 -->
        <h3>sku信息</h3>
        <el-row :gutter="20">
          <el-table :rules="rules" :data="goodsTableData" style="width: 100%" max-height="250">
            <el-table-column prop="price" label="单价(元)" width="120" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="请输入单价"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="realPrice" label="真实价格(元)" width="120" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.realPrice" placeholder="请输入真实价格"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品条码" width="180" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.code" placeholder="请输入商品条码"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="商品单位" width="160" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.unit" placeholder="请选择单位" clearable>
                  <el-option-group label="数量单位">
                    <el-option value="1" label="件(piece)"></el-option>
                    <el-option value="2" label="个(each)"></el-option>
                    <el-option value="3" label="套(set)"></el-option>
                    <el-option value="4" label="箱(box)"></el-option>
                    <el-option value="5" label="包(pack)"></el-option>
                    <el-option value="6" label="瓶(bottle)"></el-option>
                    <el-option value="7" label="袋(bag)"></el-option>
                  </el-option-group>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="productWeight" label="商品重量(g)" width="140" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.productWeight" placeholder="请输入商品重量(g)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productLength" label="商品长度(cm)" width="140" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.productLength" placeholder="请输入商品长度(cm)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productWidth" label="商品宽度(cm)" width="140" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.productWidth" placeholder="请输入商品宽度(cm)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productHeight" label="商品高度(cm)" width="140" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.productHeight" placeholder="请输入商品高度(cm)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productVolume" label="商品体积(cm³)" width="140" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.productVolume" disabled placeholder="" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120" align="center">
              <template #default="scope">
                <el-button link type="warning" size="large" @click.prevent="deleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="mt-4" type="primary" plain style="width: 100%; margin-top: 30px;" @click="onAddItem">+ 继续添加
          </el-button>
        </el-row>
      </div>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="reset">取消</el-button>
        <el-button type="primary" @click="submitData">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.editor {
  padding: 20px;
  border-radius: 8px;
}

.rich-text-editor {
  height: 300px;
  /* 修改为更小的高度 */
  width: 100%;
  max-width: 800px;
}

:deep(.ql-toolbar) {
  border-radius: 4px 4px 0 0;
  border-color: #dcdfe6;
}

:deep(.ql-container) {
  border-radius: 0 0 4px 4px;
  border-color: #dcdfe6;
}

:deep(.ql-editor) {
  min-height: 100px;
}
</style>